<template>
  <div>
    <el-row class="layout-top">
      <el-col :span="4">
        <el-button class="btn-add" @click="onAddClick">{{ $t('message.medias.add') }}</el-button>
      </el-col>
      <!-- <el-col :span="8" :offset="12" class="flex-container">
        <el-input v-model="name" placeholder="布局名称" class="inline"></el-input>
        <el-button class="inline">上一页</el-button>
        <el-button class="inline">下一页</el-button>
      </el-col> -->
    </el-row>
    <el-table :data="constLayouts" :header-cell-style="{background:'#EBEEF5'}" style="width: 100%">
      <el-table-column label="ID" prop="id"></el-table-column>
      <!-- <el-table-column :label="$t('message.name')" prop="name"></el-table-column> -->
      <el-table-column :label="$t('message.medias.layoutType')" prop="layoutType"></el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="onViewClick(scope.row)">{{$t('message.medias.view')}}</el-button>
          <el-button type="text" size="small" @click="onEditClick(scope.row)" v-show="scope.row.layoutType=='custom'">{{$t('message.medias.edit')}}</el-button>
          <el-button type="danger" size="small" @click="onDelClick(scope.row)" v-show="scope.row.layoutType=='custom'">{{$t('message.medias.del')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="showView" :title="$t('message.medias.layoutDetail')">
      <div>
        <el-row>
          <el-col :span="24">
            <div id="view-layout"></div>
          </el-col>
        </el-row>
        
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showEdit" :title="$t('message.medias.selectLayout')">
      <div>
        <!-- <el-row style="float:left"> -->
          <!-- <el-col :span="4"> -->
            <label style="marginRight:30px;">{{ $t('message.medias.id') }}</label>
          <!-- </el-col> -->
          <!-- <el-col :span="20"> -->
            <el-input :disabled="isEdit" v-model="curRow.id" placeholder="ID"></el-input>
          <!-- </el-col> -->
        <!-- </el-row> -->
        <!-- <el-row>
          <el-col :span="4">
            <span>{{ $t('message.medias.layout') }}</span>
          </el-col>
          <el-col :span="20">
            <el-input v-model="curRow.name" placeholder="布局名"></el-input>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="24">
            <div id="edit-layout"></div>
          </el-col>
        </el-row>
        <p v-show="isOverlapping" style="color:red;">{{$t('message.medias.overlapTip')}}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn-add" @click.prevent="onNewWindow">{{$t('message.medias.newWin')}}</el-button>
        <el-button @click="showEdit = false">{{$t('message.cancel')}}</el-button>
        <el-button type="primary" @click="onSaveLayout">{{$t('message.ok')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { api } from "@/libs/api";
import setForm from "@/components/setForm";
import mylist from "@/components/MyList";
import ebus from "@/libs/ebus";
import { VLayout } from "@/libs/layout.js";
import { LcdPreview } from "@/libs/canvas.js";
import { mapState } from "vuex";
import topTable from "@/components/topTable";
import { setTimeout } from "timers";
export default {
  created() {
    this.getCfg();
    
  },
  computed: {
    ...mapState(["media","system"]),
    curTopic() {
      if (this.system.isSpecialType) {
        return "mediaapp";
      } else {
        return "zhishen";
      }
    },
  },
  data() {
    return {
      name: "",
      showView: false,
      showEdit: false,
      isEdit: false,
      isOverlapping: false,
      curRow: {
        id: "",
        name: "",
        layoutType: "",
        base: {
          h: 1920,
          v: 1080
        },
        method: "",
        subScreen: []
      },
      preview: new VLayout(),
      viewLayout: new LcdPreview(),
      editLayout: new VLayout(),
      show: false,
      curLayer: {
        left: 0,
        top: 0,
        right: 0,
        bottom: 0
      },
      currentRow: {
        id: "fullScreen",
        name: "fullScreen",
        layoutType: "constant",
        base: {
          h: 1920,
          v: 1080
        },
        subScreen: [
          {
            left: 0,
            top: 0,
            right: 1920,
            bottom: 1080
          }
        ]
      },
      constLayouts: [
        {
          id: "fullScreen",
          name: "fullScreen",
          layoutType: "constant",
          base: {
            h: 1920,
            v: 1080
          },
          subScreen: [
            {
              left: 0,
              top: 0,
              right: 1920,
              bottom: 1080
            }
          ]
        },
        {
          id: "splitScreenBy2",
          name: "splitScreenBy2",
          layoutType: "constant",
          base: {
            h: 1920,
            v: 1080
          },
          subScreen: [
            {
              left: 0,
              top: 0,
              right: 960,
              bottom: 1080
            },
            {
              left: 960,
              top: 0,
              right: 1920,
              bottom: 1080
            }
          ]
        }
      ],

      layout: {
        _id: -1,
        id: "default",
        name: "default",
        buildIn: 0,
        multiScreenX: 1,
        multiScreenY: 1,
        multiScreen: "",
        windowList: ""
      },
      cfg: {
        checkable: false,
        showHead: true,
        columns: [
          {
            width: "auto",
            name: "windowId"
          }
        ],
        operation: {
          text: this.$t("common.operation"),
          width: "auto",
          actions: [
            {
              icon: "glyphicon glyphicon-trash",
              doClick: this.onDel
            }
          ]
        }
      },
      multiScreenX: 1,
      multiScreenY: 1,
    };
  },
  mounted() {
    ebus.on('overlapping', (bools) => {
      this.isOverlapping = bools
    })
  },
  components: {
    setForm,
    mylist,
    topTable
  },
  methods: {
    handleCurrentChanges(val, index) {
      var currentRow = this.currentRow;
      for (var key in val) {
        if (Array.isArray(val[key])) {
          currentRow[key].splice(0, currentRow[key].length);
          val[key].forEach((item, arrIndex) => {
            currentRow[key].splice(arrIndex, 1, item);
          });
        } else {
          currentRow[key] = val[key];
        }
      }
      this.show = true;
    },
    hasRemote(index) {
      var res = false;
      if (this.currentRow.srcAddr && this.currentRow.srcAddr.length) {
        this.currentRow.srcAddr.forEach(val => {
          if (val === `remote:${index - 1}`) {
            res = true;
            return;
          }
        });
      }
      return res;
    },
    hasLocal(index) {
      var res = false;
      if (this.currentRow.srcAddr && this.currentRow.srcAddr.length) {
        this.currentRow.srcAddr.forEach(val => {
          if (val === `local:${index - 1}`) {
            res = true;
            return;
          }
        });
      }
      return res;
    },
    getCfg() {
      api.onRequest(
        `$method.$query.${this.curTopic}.layout.cfg`,
        "{}",
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            
            this.constLayouts.splice(0, this.constLayouts.length);
            res.data.items.forEach(item => {
              this.constLayouts.push(item);
            });
          }
        }.bind(this)
      );
    },
    init(val) {
      var preview = document.getElementById("edit-layout");
      var offsetW = preview.offsetWidth;
      var offsetH = preview.offsetHeight;
      var scale = 1;
      let multiScreenX = this.multiScreenX;
      let multiScreenY = this.multiScreenY;
      var maxCount = 256;

      this.preview.init("edit-layout", {
        width: offsetW,
        height: offsetH,
        multiScreenX: 1,
        multiScreenY: 1,
        maxWindowCnt: maxCount
      });
      this.preview.updateBg({
        color: {
          hex: "#666"
        }
      });
      var windowList = [];

      val.subScreen.forEach((item, index) => {
        windowList.push({
          windowId: index,
          layer: index,
          coordinate: {
            topHoriz: (item.left * 12) / 1920,
            topVerti: (item.top * 12) / 1080,
            bottomHoriz: (item.right * 12) / 1920,
            bottomVerti: (item.bottom * 12) / 1080
          }
        });
      });
      if (windowList && windowList.length > 0) {
        this.preview.updateByWindowList(windowList);
      }
    },
    drawEditLayout(val) {
      var preview = document.getElementById("edit-layout");
      var offsetW = preview.offsetWidth;
      var offsetH = preview.offsetHeight;
      this.preview.init("edit-layout", {
        width: offsetW,
        height: offsetH,
        multiScreenX: 1,
        multiScreenY: 1,
        maxWindowCnt: 256,
        base: {
          width: 1920,
          height: 1080
        }
      });
      // this.preview.updateBg({
      //   color: {
      //     hex: '#666'
      //   }
      // })
      var windowList = [];
      if (val && val.subScreen && val.subScreen.length) {
        val.subScreen.forEach((item, index) => {
          if (item.left || item.top || item.right || item.bottom) {
            windowList.push({
              windowId: index,
              layer: index,
              coordinate: {
                left: (item.left * 12) / 1920,
                top: (item.top * 12) / 1080,
                right: (item.right * 12) / 1920,
                bottom: (item.bottom * 12) / 1080
              }
            });
          }
        });
      }

      if (windowList && windowList.length > 0) {
        this.preview.updateByWindowList(windowList);
      }
    },
    onNewWindow() {
      var maxCount = 256;
      if (this.preview.getWindowListCnt() >= maxCount) {
        toast.e(this, this.$t("common.fail"), this.$t("error.reachLimit"));
      } else {
        this.preview.setMode("newWindow");
      }
    },
    onViewClick(row) {
      this.showView = true;
      setTimeout(() => {
        this.drawDialogLayout(row);
      }, 100);
    },
    onEditClick(row) {
      this.curRow.id = row.id
      // this.curRow.name = row.id
      this.curRow.layoutType = row.layoutType
      this.curRow.base = row.base
      this.curRow.subScreen = row.subScreen
      this.curRow.method = "update"
      this.showEdit = true
      this.isEdit = true;
      setTimeout(() => {
        this.drawEditLayout(row);
      }, 100);
    },
    onAddClick() {
      if(this.constLayouts.length >= 32) {
        this.notification('WARNING',this.$t('message.medias.layoutNumTip'))
        return
     }
     this.isOverlapping = false;
      this.showEdit = true;
      this.isEdit = false;
      this.curRow = {
        id: "",
        name: "",
        layoutType: "",
        method: "add",
        base: {
          h: 1920,
          v: 1080
        },
        subScreen: []
      };
      setTimeout(() => {
        this.drawEditLayout(this.curRow);
      }, 100);
    },
    drawDialogLayout(row) {
      var preview = document.getElementById("view-layout");
      var offsetW = preview.offsetWidth;
      var offsetH = preview.offsetHeight;
      let xScale = offsetW / row.base.h;
      let yScale = offsetH / row.base.v;

      this.viewLayout.init("view-layout", {
        width: offsetW,
        height: offsetH,
        multiScreenX: 1,
        multiScreenY: 1,
        maxWindowCnt: 256
      });
      this.viewLayout.updateBg({
        color: {
          hex: "#666"
        }
      });

      var windowList = [];
      if (row && row.subScreen) {
        row.subScreen.forEach((item, index) => {
          if (item.left || item.top || item.right || item.bottom){
            windowList.push({
              windowId: index,
              layer: index,
              coordinate: {
                left: item.left,
                top: item.top,
                right: item.right,
                bottom: item.bottom
              }
            });
          }          
        });
      }

      if (windowList && windowList.length > 0) {
        this.viewLayout.updateWindows(windowList, {
          xScale: xScale,
          yScale: yScale
        });
      }
    },
    onSaveLayout() {
      if(this.isOverlapping) return;
      if(!this.isEdit) {
        let curID = _.map(this.constLayouts, 'id');
        if(_.includes(curID, this.curRow.id)) {
          this.notification('error', this.$t('message.medias.layoutAddTip'))
          return
        }
      }
    
      let windowList = this.preview.getWindowList();
      var layout = {
        id: this.curRow.id,
        // name: this.curRow.name,
        layoutType: 'custom',
        base: {
          h: 1920,
          v: 1080
        },
        subScreen: []
      };
      if (windowList && windowList.length) {
        windowList.forEach(item => {
          layout.subScreen.push({
            left: (item.coordinate.left * 1920) / 12,
            top: (item.coordinate.top * 1080) / 12,
            right: (item.coordinate.right * 1920) / 12,
            bottom: (item.coordinate.bottom * 1080) / 12
          });
        });
      }
      
      for (var i = 0; i < 9; i++){
        if (!layout.subScreen[i]) {
          layout.subScreen.push({
            left: 0,
            top: 0,
            right: 0,
            bottom: 0
          })
        }
      }
      api.onRequest(
        `$method.$${this.curRow.method}.${this.curTopic}.layout.cfg`,
        JSON.stringify([layout]),
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.notification("Success", "");
            this.getCfg();
            this.showEdit = false;
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    },
    onDelClick(row) {
      api.onRequest(
        `$method.$del.${this.curTopic}.layout.cfg`,
        JSON.stringify([row.id]),
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.notification("Success", "");
            this.getCfg();
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    }
  }
};
</script>

<style scoped>
.row-height {
  height: 36px;
}
.layout-preview {
  height: 400px;
}
#view-layout,
#edit-layout {
  height: 400px;
}
.el-col .position {
  width: 100%;
}
.preview {
  height: 100%;
  width: 100%;
}
.layout-top {
  margin-top: 10px;
  margin-bottom: 10px;
}
.btn-add {
  float: left;
  margin-left: 15px;
}
.flex-container {
  display: flex;
}
.inline {
  height: 40px;
}
</style>

